<template>
  <!-- 账号列表 -->
  <section class="add">
    <!-- 头部筛选区域 -->
    <section class="top">
      <el-page-header title="返回列表" @back="goBack">
        <template #content>
          <span class="text-large font-600 mr-3"> {{ headerContent }} </span>
        </template>
      </el-page-header>
    </section>
    <section class="content">
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-position="top"
      >
        <!-- 第一步 -->
        <el-form-item
          label="课表名称"
          prop="title"
          :label-width="80"
          v-show="currentStep == 0"
        >
          <el-input
            v-model="form.courseTimetableName"
            autocomplete="off"
            placeholder="请输入课表名称"
          />
        </el-form-item>

        <el-row :gutter="100" v-show="currentStep == 0">
          <el-col :span="12">
            <el-form-item label="课程" prop="field" :label-width="80">
              <el-select v-model="form.courseId" placeholder="请选择课程">
                <el-option
                  v-for="item in courseList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="老师" prop="courseTeacher" :label-width="80">
              <el-select v-model="form.courseTeacher" placeholder="请选择老师">
                <el-option
                  v-for="item in teacherList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select> </el-form-item
          ></el-col>
        </el-row>

        <el-row :gutter="100" v-show="currentStep == 0">
          <el-col :span="12">
            <el-form-item label="场地" prop="agency" :label-width="80">
              <el-select v-model="form.addressId" placeholder="请选择场地">
                <el-option
                  v-for="item in addressList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                /> </el-select></el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="可约人数" prop="agency" :label-width="80">
              <el-input
                v-model="form.stuCount"
                placeholder="请输入可约人数"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>

        <el-row :gutter="100" v-show="currentStep == 0">
          <el-col :span="12">
            <el-form-item label="课程次数" prop="agency" :label-width="80">
              <el-input
                v-model="form.courseCount"
                placeholder="课程次数"
                @change="changeCourseCount"
              ></el-input></el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item
              label="课程时长"
              prop="paymentStatus"
              :label-width="80"
            >
              <el-input
                v-model="form.duration"
                placeholder="课程时长"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="100" v-show="currentStep == 0">
          <el-col :span="12">
            <el-form-item label="标签" prop="courseTags" :label-width="80">
              <el-input
                v-model="form.courseTags"
                placeholder="标签"
              ></el-input> </el-form-item
          ></el-col>

          <el-col :span="12">
            <el-form-item
              label="取消要求提前天数"
              prop="cancelRequire"
              :label-width="80"
            >
              <el-input
                v-model="form.cancelRequire"
                placeholder="请输入取消要求提前天数"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>

        <!-- 第二步 -->
        <el-table :data="form.timeTableList" v-show="currentStep == 1">
          <!-- 自定义日期 -->
          <el-table-column prop="timetableDate" label="日期">
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.timetableDate"
                type="date"
                placeholder="选择日期"
              />
            </template>
          </el-table-column>
          <!-- 自定义开始时间 -->
          <el-table-column prop="timetableStartTime" label="开始时间">
            <template #default="scope">
              <el-time-select
                v-model="scope.row.timetableStartTime"
                :max-time="scope.row.timetableEndTime"
                placeholder="开始时间"
                step="00:15"
                start="00:00"
                end="23:59"
              />
            </template>
          </el-table-column>
          <!-- 自定义结束时间 -->
          <el-table-column prop="timetableEndTime" label="结束时间">
            <template #default="scope">
              <el-time-select
                v-model="scope.row.timetableEndTime"
                :min-time="scope.row.timetableStartTime"
                placeholder="结束时间"
                step="00:15"
                start="00:00"
                end="23:59"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </section>
    <!-- 按钮框 -->
    <section class="bottom mb-4">
      <el-button @click="goBack">取消</el-button>
      <el-button
        v-show="currentStep == 0"
        type="primary"
        :loading="isLoading"
        @click="changeStep(1)"
        >下一步</el-button
      >
      <el-button
        v-show="currentStep == 1"
        type="primary"
        :loading="isLoading"
        @click="changeStep(0)"
        >上一步</el-button
      >
      <el-button
        v-show="currentStep == 1"
        type="primary"
        :loading="isLoading"
        @click="submitForm(formRef)"
        >确认</el-button
      >
    </section>
  </section>
</template>

<script setup>
import dayjs from "dayjs";
import { ref, reactive, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { addRequest, updateRequest } from "@/apis/timetable.js";
import { queryListRequest as queryCourseList } from "@/apis/course.js";
import { queryTeathListRequest } from "@/apis/user.js";
import { queryListRequest as queryAddressList } from "@/apis/address.js";

const router = useRouter();
const route = useRoute();
const optionType = route.query.type;

// 当前步骤
let currentStep = ref(0);
const changeStep = (step) => {
  currentStep.value = step;
};

// header的内容
let headerContent = computed(() => {
  let str = optionType == "edit" ? "编辑课程：" : "新增课程：";
  currentStep.value == 0 ? (str += "础信息") : (str += "课程表");
  return str;
});

// form表单参数
const ruleFormRef = ref(null);
let form = reactive({
  courseTimetableName: "", //课程表名称
  courseId: "", //课程id
  courseTeacher: "", //老师id
  addressId: "", // 场地ID
  courseTags: "", //标签
  cancelRequire: "", //取消要求提前天数
  courseCount: "", //课程次数
  stuCount: "", //可预约人数
  duration: "", //课程时长
  cancelRequire: "", //取消要求天数
  timeTableList: [], //课表列表
});

if (optionType == "edit") {
  headerContent = "编辑课程";
  let editObj = JSON.parse(route.query.rowData);
  form.id = editObj.id;
  Object.keys(form).forEach((item) => {
    if (editObj[item]) {
      form[item] = editObj[item];
      if (item == "timeTableList") {
        form[item].forEach((a) => {
          a.timetableDate = dayjs(a.timetableDate).format("YYYY-MM-DD");
          a.timetableStartTime = dayjs(a.timetableStartTime).format("HH:mm");
          a.timetableEndTime = dayjs(a.timetableEndTime).format("HH:mm");
        });
      }
    }
  });
}

// 课程列表
const courseList = ref([]);
queryCourseList({
  pageNum: 1,
  pageSize: 1000,
}).then((res) => {
  courseList.value = res.data.map((item) => {
    return {
      value: item.id,
      label: item.courseName,
    };
  });
});
// 场地列表
const addressList = ref([]);
queryAddressList({
  pageNum: 1,
  pageSize: 1000,
}).then((res) => {
  addressList.value = res.data.map((item) => {
    return {
      value: item.id,
      label: item.addressName,
    };
  });
});

// 老师列表
const teacherList = ref([]);
queryTeathListRequest({
  pageNum: 1,
  pageSize: 1000,
  accountType: "3",
}).then((res) => {
  teacherList.value = res.data.map((item) => {
    return {
      value: item.id,
      label: item.nickName,
    };
  });
});

// 改变课程次数
const changeCourseCount = () => {
  let timeTableList = form.timeTableList;
  // 如果数组长度小于课程次数，进行填充
  while (timeTableList.length <= form.courseCount) {
    timeTableList.push({
      timetableDate: "",
      timetableStartTime: "",
      timetableEndTime: "",
    });
  }

  // 如果数组长度大于课程次数，进行删除
  if (timeTableList.length > form.courseCount) {
    timeTableList.splice(form.courseCount);
  }

  console.log(timeTableList, "timeTableList");
  form.timeTableList = timeTableList;
};

// form 表单规则
const rules = reactive({
  name: [{ required: "true", message: "请输入项目名称", trigger: "blur" }],
  resPerson: [
    { required: "true", message: "请选择项目责任人", trigger: "change" },
  ],
  content: [{ required: "true", message: "请输入项目描述", trigger: "blur" }],
});
// 提交loading
let isLoading = ref(false);
// form提交函数
const submitForm = () => {
  if (!ruleFormRef) return;
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      // 打开loding
      isLoading.value = true;
      // 格式化数据
      form.timeTableList = form.timeTableList.map((item) => {
        return {
          timetableDate: dayjs(item.timetableDate).format(
            "YYYY-MM-DD 00:00:00"
          ),
          timetableStartTime: dayjs(
            dayjs(item.timetableDate).format("YYYY-MM-DD") +
              item.timetableStartTime
          ).format("YYYY-MM-DD HH:mm:ss"),
          timetableEndTime: dayjs(
            dayjs(item.timetableDate).format("YYYY-MM-DD") +
              item.timetableEndTime
          ).format("YYYY-MM-DD HH:mm:ss"),
        };
      });
      // 请求接口
      if (optionType == "edit") {
        await updateRequest(form);
      } else {
        await addRequest(form);
      }
      // 关闭loading
      isLoading.value = false;
      // 路由返回
      goBack();
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
//  路由返回函数
const goBack = () => {
  router.back();
};
</script>
<style lang="less" scoped>
.add {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  .top {
    display: flex;
    .el-input {
      width: 300px;
      margin-right: 20px;
    }
  }
  .content {
    width: 100%;
    flex: 1;
    overflow-x: hidden;
    overflow-y: scroll;
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .bottom {
    display: flex;
    justify-content: end;
  }
}
</style>
